<?php

namespace App\Http\Controllers\Manage;


use App\Model\Product;
use App\Model\ProductAttachment;
use App\Model\ProductPicture;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;

use App\Model\ProductCategory;
use OSS\OssClient;
use OSS\Core\OssException;
class ProductController extends Controller
{

    /**
     * //定义一个数组  用来排列查询选项或列表头
     * @var array
     */
    protected static $field = [
        ['id'=>1,'navigation'=>'编号'],
        ['id'=>2,'navigation'=>'更新时间'],
        ['id'=>3,'navigation'=>'权重'],
        ['id'=>4,'navigation'=>'一级分类'],
        ['id'=>5,'navigation'=>'二级分类'],
        ['id'=>6,'navigation'=>'产品名称'],
        ['id'=>7,'navigation'=>'产品估价'],
        ['id'=>8,'navigation'=>'制作周期'],
        ['id'=>9,'navigation'=>'适用企业'],
        ['id'=>10,'navigation'=>'绩效系数'],
    ];

    /**
     * 产品列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        #产品搜索条件
        $search = Input::get('type');
        $param = Input::get('param');
        $orderBy = Input::get('orderBy');
        $start_time = Input::get('start_time');
        $end_time = Input::get('end_time');
        $page = Input::get('page');
        $count = Input::get('count');

        $obj = new Product();
        if (!empty($start_time)){
            $obj = $obj->where('update_time','>=',$start_time);
        }
        if (!empty($end_time)){
            $obj = $obj->where('update_time','<=',$end_time);
        }
        if($search == 1){
            $obj = $obj->where('id','like',"%$param%");
        }elseif ($search == 2){
            $obj = $obj->where('update_time','like',"%$param%");
        }elseif ($search == 3){
            $obj = $obj->where('rank','like',"%$param%");
        }elseif ($search == 4){
            $fc = ProductCategory::where('name','like',"%$param%")->get();
            $id = array();
            foreach ($fc as $k=>$v){
                $c = ProductCategory::where('parent_id',$v->id)->get();
                foreach ($c as $value){
                    $id[] = $value->id;
                }
            }
            $obj = $obj->whereIn('category',$id);
        }elseif ($search == 5){
            $c = ProductCategory::where('name','like',"%$param%")->get();
            $id = array();
            foreach ($c as $k=>$v){
                $id[] = $v->id;
            }
            $obj = $obj->whereIn('category',$id);
        }elseif ($search == 6){
            $obj = $obj->where('name','like',"%$param%");
        }elseif ($search == 7){
            $obj = $obj->where('price','like',"%$param%");
        }elseif ($search == 8){
            $obj = $obj->where('period','like',"%$param%");
        }elseif ($search == 9){
            $obj = $obj->where('firm','like',"%$param%");
        }elseif ($search == 10){
            $obj = $obj->where('performance','like',"%$param%");
        }elseif ($search == 100){
            $obj = $obj->where('status',$param);
        }
        #判断时间排序
        if($orderBy == 1){
            $obj = $obj->orderBy('update_time','ASC');
        }elseif($orderBy == 2){
            $obj = $obj->orderBy('update_time','DESC');
        }else{
            $obj = $obj->orderBy('rank','DESC')->orderBy('update_time','DESC');
        }


        #获取产品信息
        $product = $obj->paginate(20);
        if(empty($page)){
            $count = $obj->count();
        }

        $category = array();
        foreach ($product as $k=>$v){
            $categoryTwo = ProductCategory::where('id',$v->category)->first();
            $category[$k]['two'] = $categoryTwo->name;
            $categoryOne = ProductCategory::where('id',$categoryTwo->parent_id)->first();
            $category[$k]['one'] = $categoryOne->name;
        }
        $navigation = self::$field;
        return view('manage.product.product_list',[
            'product'=>$product,
            'navigation'=>$navigation,
            'search'=>$search,
            'param'=>$param,
            'orderBy'=>$orderBy,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'category'=>$category,
            'count'=>$count,
            'active1'=>5,
            'active2'=>1
        ]);
    }

    /**
     * 载入添加产品页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function add()
    {
        #获取所有一级分类
        $category_one = ProductCategory::where('level',1)->get();
        #获取第一个一级分类的子分类
        $category_two = ProductCategory::where('parent_id',$category_one[0]->id)->get();
        return view('manage.product.product_add',['category_one'=>$category_one,'category_two'=>$category_two,'active1'=>5,'active2'=>2]);
    }

    /**
     * 添加产品接口
     * @return array
     */
	public function productAdd()
	{
		$product = new Product();
		$product->category = Input::get('category');//所属类别
		$product->name = Input::get('name');//产品名称
		$product->rank = Input::get('rank');//产品权重
		$product->price = Input::get('price');//产品估价
		$product->period = Input::get('period');//制作周期
		$product->firm = Input::get('firm');//适用企业
		$product->performance = Input::get('performance');//绩效系数
		$product->service = Input::get('content');//服务内容
		$product->brief = Input::get('brief');//产品简介
		
		if($product->save()){
			return [
				'code'=>100,
				'msg'=>'添加成功！'
			];
		}else{
			return [
				'code'=>101,
				'msg'=>'添加失败！'
			];
		}
	}

    /**
     * 根据一级分类获取二级分类接口
     * @return array
     */
	public function getTwo()
    {
        $id = Input::get('parent_id');
		$category_two = ProductCategory::where('parent_id',$id)->get();
		if($category_two){
			return [
				'code'=>100,
				'msg'=>'获取成功',
				'category_two'=>$category_two
			];
		}else{
			return [
				'code'=>101,
				'msg'=>'获取失败！'
			];
		}
    }

    /**
     * #载入修改页
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getProduct($id)
    {
		#获取产品信息
		$product = Product::where('id',$id)->first();
		#获取二级分类信息
		$category_two = ProductCategory::where('id',$product->category)->first();
		#获取一级分类信息
		$category_one = ProductCategory::where('id',$category_two->parent_id)->first();
		#获取所有一级分类
		$one = ProductCategory::where('level',1)->get();
		#获取所有该产品对应的一级分类下的所有二级分类
		$two = ProductCategory::where('level',2)->get();
		return view('manage.product.product_update',['product'=>$product,'category_two'=>$category_two,'category_one'=>$category_one,'one'=>$one,'two'=>$two,'active1'=>5,'active2'=>1]);
    }

    /**
     * #修改产品
     * @return array
     */
	public function productUpdate(){
//	    return ['a'=>Input::all()];
		$product = Product::find(Input::get('id'));
		$product->category = Input::get('category');//所属类别
		$product->name = Input::get('name');//产品名称
		$product->rank = Input::get('rank');//产品权重
		$product->price = Input::get('price');//产品估价
		$product->period = Input::get('period');//制作周期
		$product->firm = Input::get('firm');//适用企业
		$product->performance = Input::get('performance');//绩效系数
		$product->service = Input::get('content');//服务内容
		$product->brief = Input::get('brief');//产品简介
		
		if($product->save()){
			return [
				'code'=>100,
				'msg'=>'修改成功！'
			];
		}else{
			return [
				'code'=>101,
				'msg'=>'修改失败！'
			];
		}
	}

    /**
     * #删除产品
     * @return array
     */
	public function productDelete(){
	    $id = Input::get('id');
		$delete = Product::where('id',$id)->delete();
		if($delete){
			return [
				'code'=>100,
				'msg'=>'删除成功！'
			];
		}else{
			return [
				'code'=>101,
				'msg'=>'删除失败！'
			];
		}
	}

    /**
     * #批量操作
     */
	public function batch(){
		
	}

    /**
     * #启用、禁用
     * @return array
     */
    public function setStatus() {
        $id = Input::get('id');
        $status = Input::get('status');
            if($status == 1) {
                $del = Product::where('id',$id)->update(['status'=>1]);
                $msg = '启用成功！';
            }else{
                $del = Product::where('id',$id)->update(['status'=>0]);
                $msg = '禁用成功！';
            }
            if(!$del){
                return [
                    'code'=>101,
                    'msg'=>'设置失败！'
                ];
            }
            return [
                'code'=>100,
                'msg'=>$msg
            ];
    }


    /**
     * #管理图片
     * @param $pid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function productPicture($pid){
        #获取已经上传的图片信息
        $picture = ProductPicture::where('link_id',$pid)->get();
        return view('manage.product.product_picture',['picture'=>$picture,'pid'=>$pid,'active1'=>5,'active2'=>1]);
    }

    /**
     * #提交产品图片存入数据库
     * @return array
     */
    public function pictureAdd(){
        #设置oss参数
        $ossClient = $this->oss();
        $id = Input::get('link_id');
        $rank = Input::get('rank');
        $content = Input::get('content');
        $path = Input::get('path');
        $name = preg_replace('/.*\//','',$path);
        if(empty($name) || empty($content)){
            return [
                'code'=>102,
                'msg'=>'缺少参数！'
            ];
        }
        $map = ProductPicture::insert([
            'link_id' => $id,
            'name' => $name,
            'rank' => $rank,
            'content' => $content,
            'path'=> $path
        ]);
        if ($map) {
            return [
              'code'=>100,
                'msg'=>'上传成功！'
            ];
        } else {
            try {
                $ossClient->deleteObject($this->bucket, $name);
            } catch (OssException $e) {
            }
            return [
                'code'=>101,
                'msg'=>'上传失败！'
            ];
        }

    }
    /**
     * 修改图片文字描述
     * @return array
     */
    public function setContent()
    {
        $content = Input::get('content');
        $id = Input::get('id');
        ProductPicture::where('id',$id)->update(['content'=>$content]);
        return [
            'code'=>100,
            'msg'=>'修改成功！'
        ];
    }
    /**
     * //删除图片
     * @return array|null
     */
    public function deletePicture() {
        $id = Input::get('id');
        $name = Input::get('name');
        $res = null;
        $ossClient = $this->oss();

        $del = ProductPicture::where('id',$id)->delete();
        if($del) {
            $res = [
                'code' => 100,
                'msg' => '删除成功!'
            ];
            try {
                $ossClient->deleteObject($this->bucket, $name);
            } catch (OssException $e) {
//                        print $e->getMessage();
            }
        }
        else {
            $res = [
                'code' => 101,
                'msg' => '删除失败!'
            ];
        }
        return $res;
    }

    /**
     * #设置图片状态
     * @return array
     */
    public function pictureStatus(){
        $id = Input::get('id');
        $status = Input::get('status');
        if($status == 1) {
            $del = ProductPicture::where('id',$id)->update(['status'=>1]);
            $msg = '启用成功！';
        }else{
            $del = ProductPicture::where('id',$id)->update(['status'=>0]);
            $msg = '禁用成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

    /**
     * #管理附件
     * @param $pid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function productAnnex($pid){
        #获取已经上传的附件信息
        $annex = ProductAttachment::where('link_id',$pid)->get();
        return view('manage.product.product_affix',['annex'=>$annex,'pid'=>$pid,'active1'=>5,'active2'=>1]);
    }

    /**
     * #提交产品附件存入数据库
     * @return array
     */
    public function annexAdd(){
        #设置oss参数
        $ossClient = $this->oss();
        $id = Input::get('link_id');
        $path = Input::get('path');
        $name = preg_replace('/.*\//','',$path);
        $map = ProductAttachment::insert(['link_id' => $id, 'name' => $name, 'path' => $path]);
        if ($map) {
            return [
                'code' => 100,
                'msg' => '上传成功！'
            ];
        } else {
            try {
                $ossClient->deleteObject($this->bucket, $name);
            } catch (OssException $e) {
            }
            return [
                'code' => 101,
                'msg' => '上传失败！'
            ];
        }
    }

    /**
     * //删除附件
     * @return array|null
     */
    public function deleteAnnex() {
        $id = Input::get('id');
        $name = Input::get('name');
        $res = null;
        $ossClient = $this->oss();

        $del = ProductAttachment::where('id',$id)->delete();
        if($del) {
            $res = [
                'code' => 100,
                'msg' => '删除成功!'
            ];
            try {
                $ossClient->deleteObject($this->bucket, $name);
            } catch (OssException $e) {
//                        print $e->getMessage();
            }
        }
        else {
            $res = [
                'code' => 101,
                'msg' => '删除失败!'
            ];
        }
        return $res;
    }

    /**
     * #设置图片状态
     * @return array
     */
    public function annexStatus(){
        $id = Input::get('id');
        $status = Input::get('status');
        if($status == 1) {
            $del = ProductAttachment::where('id',$id)->update(['status'=>1]);
            $msg = '启用成功！';
        }else{
            $del = ProductAttachment::where('id',$id)->update(['status'=>0]);
            $msg = '禁用成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

}
